import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_constraintlayout/flutter_constraintlayout.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wch/constant/event_bus_global.dart';
import 'package:wch/constant/resource_constant.dart';
import 'package:wch/helper/user_wrap_helper.dart';
import 'package:wch/model/ble.dart';
import 'package:wch/model/patient_detail.dart';
import 'package:wch/model/patient_list.dart';
import 'package:wch/page/match_device.dart';
import 'package:wch/page/set_wifi.dart';
import 'package:wch/utils/navigator_utils.dart';
import 'package:wch/utils/toast_utils.dart';
import 'package:wch/widget/common_widget.dart';
import 'package:wch/widget/padding_widget.dart';
import 'package:wch/widget/text_widget.dart';

import '../model/patient_label_list.dart';
import '../native/net_business.dart';
import '../utils/log_utils.dart';
import '../utils/text_utils.dart';

class DeliveryUserPage extends StatefulWidget {
  DeliveryUserPage({super.key, required this.bleModel});

  BleModel bleModel;
  @override
  State<DeliveryUserPage> createState() => _DeliveryUserPageState();
}

class _DeliveryUserPageState extends State<DeliveryUserPage> {
  // List<String> names = [
  //   '李四李四',
  //   '张三',
  //   '博尔济吉特氏·苏拉玛姑',
  //   '李四李四',
  //   '博尔济吉特氏·苏拉玛姑',
  //   '李四李四',
  //   '张三',
  //   '博尔济吉特氏·苏拉玛姑',
  //   '李四李四',
  // ];
  List<UserWrapModel> userList = [];

  int checkedIndex = -1;

  List<List<PatientLabelListShopLabelList>?> labelList = [];

  @override
  Widget build(BuildContext context) {
    return CommonScaffold(
        title: '分配用户',
        body: Container(
          color: Color(0xFFF8F9FB),
          margin: EdgeInsets.all(15),
          child: Center(
            child: Column(
              children: userList.isEmpty
                  ? [
                      VerPadding(98.h),
                      Image.asset(
                        deliveryEmptyPng,
                        width: 71.w,
                        height: 52.h,
                      ),
                      VerPadding(4.h),
                      F12TitleText('没有未分配用户', color: Color(0xFF868686)),
                    ]
                  : [
                      Expanded(
                        child: ListView.separated(
                            itemBuilder: (ctx, id) {
                              return _getItem(id);
                            },
                            separatorBuilder: (ctx, id) {
                              return Divider(
                                  height: 10,
                                  thickness: 10,
                                  color: Color(0xFFF8F9FB));
                            },
                            itemCount: userList.length),
                      ),
                      Container(
                        alignment: Alignment.center,
                        margin: EdgeInsets.symmetric(horizontal: 40.w),
                        height: 140.h,
                        child: CommonBtn(
                          title: '确认分配',
                          isEnable:checkedIndex != -1,
                          callback: () {

                            if (checkedIndex == -1) {
                              ToastUtils.showToast(msg: '请先选择患者');
                              return;
                            }
                            widget.bleModel.userModel!.name = userList[checkedIndex].name;
                            widget.bleModel.userModel!.sex = userList[checkedIndex].sex;
                            widget.bleModel.userModel!.mobile = userList[checkedIndex].mobile;
                            NavigatorUtil.replace(context, MatchDevicePage(model: userList[checkedIndex], bleModel: widget.bleModel, labelList: labelList![checkedIndex],));

                          },
                        ),
                      )
                    ],
            ),
          ),
        ));
  }

  @override
  void initState() {
    initData();

    globalEventBus.on<RefreshUserModel>().listen((onData){
      initData();
    });
  }

  void initData() {
    NetBusiness().patientList(1, '', 10000).then((value) {
      setState(() {
        userList.clear();
        labelList.clear();
        for(int i = 0; i < value.data!.data!.length; i ++) {
          PatientListDataData data = value.data!.data![i];
          if (data.deviceId == null) {
            userList.add(userWrap(data));
            labelList.add(data.shopLabelList);
          }
        }

        setState(() {
          userList;
        });
      });
    });
  }

  Widget _getItem(int id) {
    String name = userList[id].name!;
    // double maxWidth = ScreenUtil().screenWidth - 260.w;
    // double width = _getTextSize(name, ScreenUtil().screenWidth, 20).width;
    if (name.length > 3) {
      return _getItem1(id);
    } else {
      return _getItem2(id);
    }
  }

  Widget _getItem1(int id) {
    return GestureDetector(
      onTap: () {
        setState(() {
          checkedIndex = id;
        });
      },
      child: Container(
        height: 85.h,
        width: ScreenUtil().screenWidth - 30.w,
        child: ConstraintLayout(children: [
          Container(
            height: 85.h,
            width: ScreenUtil().screenWidth - 30.w,
            decoration: BoxDecoration(
                color: checkedIndex == id ? Color(0xFFEEF2FF) : Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(7.5.w))),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Row(
                  children: [
                    HorPadding(17.5.w),
                    Image.asset(
                      userList[id].sex == '男' ? patientMaleImg : patientFemaleImg,
                      width: 35.w,
                      height: 35.w,
                    ),
                    HorPadding(7.w),
                    Container(constraints: BoxConstraints(maxWidth: ScreenUtil().screenWidth-122.w), child: MyText(overflow: TextOverflow.ellipsis, userList[id].name!, color: Color(0xFF3E3F42), fontSize: 20)),
                    HorPadding(7.w),
                    Image.asset(
                      userList[id].sex == '男' ? patientMaleIcon : patientFemaleIcon,
                      width: 15.w,
                      height: 15.w,
                    )
                  ],
                ),
                Row(
                  children: [
                    HorPadding(59.5.w),
                    F14TitleText(userList[id].age == null ? '' : '${userList[id].age}岁', color: F2TextColor),
                    HorPadding(7.w),
                    F14TitleText(userList[id].mobile ?? '', color: F2TextColor),
                  ],
                )
              ],
            ),
          ).applyConstraint(
            topLeftTo: parent,
            bottomRightTo: parent,
          ),
          Offstage(
                  offstage: checkedIndex != id,
                  child: Image.asset(userCheckedIcon))
              .applyConstraint(bottomRightTo: parent, width: 40.w, height: 40.h)
        ]),
      ),
    );
  }

  Widget _getItem2(int id) {
    return GestureDetector(
      onTap: () {
        setState(() {
          checkedIndex = id;
        });
      },
      child: Container(
        height: 85.h,
        width: ScreenUtil().screenWidth - 30.w,
        child: ConstraintLayout(children: [
          Container(
            height: 85.h,
            width: ScreenUtil().screenWidth - 30.w,
            decoration: BoxDecoration(
                color: checkedIndex == id ? Color(0xFFEEF2FF) : Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(7.5.w))),
            child: Row(
              children: [
                HorPadding(17.5.w),
                Image.asset(
                  userList[id].sex == '男' ? patientMaleImg : patientFemaleImg,
                  width: 35.w,
                  height: 35.w,
                ),
                HorPadding(7.w),
                MyText(userList[id].name!, color: Color(0xFF3E3F42), fontSize: 20),
                HorPadding(7.w),
                Image.asset(
                  userList[id].sex == '男' ? patientMaleIcon : patientFemaleIcon,
                  width: 15.w,
                  height: 15.w,
                ),
                Expanded(child: Container()),
                F14TitleText(userList[id].age == null ? '' : '${userList[id].age}岁', color: F2TextColor),
                HorPadding(7.w),
                F14TitleText(userList[id].mobile ?? '', color: F2TextColor),
                HorPadding(20.w),
              ],
            ),
          ).applyConstraint(topLeftTo: parent, bottomRightTo: parent),
          Offstage(
                  offstage: checkedIndex != id,
                  child: Image.asset(userCheckedIcon))
              .applyConstraint(bottomRightTo: parent, width: 40.w, height: 40.h)
        ]),
      ),
    );
  }

  Size _getTextSize(String text, double maxWidth, double fontSize) {
    TextStyle style = TextStyle(
      fontSize: fontSize,
    );
    return TextUtils.boundingTextSize(text, style, maxWidth: maxWidth);
  }
}
